<template>
  <div class="main-container">
    <!-- 添加背景装饰元素 -->
    <div class="background-decoration">
      <div class="circle circle-1"></div>
      <div class="circle circle-2"></div>
      <div class="circle circle-3"></div>
      <div class="line line-1"></div>
      <div class="line line-2"></div>
      <div class="grid"></div>
    </div>
    <!-- 导航 -->
    <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="1">
        <el-icon style="font-size: 25px;">
          <HomeFilled />
        </el-icon>
      </el-menu-item>
      <el-menu-item index="2">考试</el-menu-item>
      <el-menu-item index="5">试题</el-menu-item>
      <el-menu-item index="6">人员</el-menu-item>
      <el-menu-item index="7">证书</el-menu-item>
    </el-menu>
    <div class="header-right-icon">
      <!-- 添加发送通知按钮 -->
      <el-popover placement="bottom" width="400" trigger="manual" :visible="notificationPopoverVisible">
        <template #reference>
          <div class="notification-icon" @click="toggleNotificationForm">
            <el-badge :value="unreadCount > 0 ? unreadCount : ''" :max="99" class="notification-badge">
              <el-icon style="font-size: 24px; cursor: pointer; margin-right: 15px;">
                <Bell />
              </el-icon>
            </el-badge>
          </div>
        </template>
        
        <!-- 通知中心/发送通知切换 -->
        <div class="notification-header">
          <div class="notification-tabs">
            <div 
              :class="['notification-tab', notificationActiveTab === 'center' ? 'active' : '']" 
              @click="notificationActiveTab = 'center'"
            >
              通知中心
            </div>
            <div 
              :class="['notification-tab', notificationActiveTab === 'send' ? 'active' : '']" 
              @click="notificationActiveTab = 'send'"
              v-if="userStore.userInfo.role === 'teacher'"
            >
              发送通知
            </div>
          </div>
        </div>

        <!-- 通知中心内容 -->
        <div v-if="notificationActiveTab === 'center'" class="notification-center">
          <div v-if="notifications.length === 0" class="empty-notifications">
            <el-empty description="暂无通知" />
          </div>
          <el-scrollbar height="350px">
            <div 
              v-for="notification in notifications" 
              :key="notification.notificationId || notification.id" 
              :class="['notification-item', userStore.userInfo.role === 'student' && !notification.readStatus ? 'unread' : '']"
              @click="viewNotification(notification.notificationId || notification.id)"
            >
              <div class="notification-priority" :class="'priority-' + notification.priority"></div>
              <div class="notification-content">
                <div class="notification-title">{{ notification.title }}</div>
                <div class="notification-brief">{{ notification.content.substring(0, 50) + (notification.content.length > 50 ? '...' : '') }}</div>
                <div class="notification-meta">
                  <span>{{ formatDate(notification.sendTime || notification.createTime) }}</span>
                  <span v-if="userStore.userInfo.role === 'student' && !notification.readStatus" class="unread-badge">未读</span>
                </div>
              </div>
            </div>
          </el-scrollbar>
          <div class="notification-pagination">
            <el-pagination
              small
              layout="prev, pager, next"
              :total="totalNotifications"
              :page-size="notificationPageSize"
              :current-page="notificationCurrentPage"
              @current-change="handleNotificationPageChange"
            />
          </div>
        </div>
        
        <!-- 发送通知表单 -->
        <div v-if="notificationActiveTab === 'send'" class="notification-form">
          <el-form :model="notificationForm" :rules="notificationRules" ref="notificationFormRef" label-position="top">
            <el-form-item label="通知标题" prop="title">
              <el-input v-model="notificationForm.title" placeholder="请输入通知标题"></el-input>
            </el-form-item>
            <el-form-item label="通知内容" prop="content">
              <el-input v-model="notificationForm.content" type="textarea" :rows="4" placeholder="请输入通知内容"></el-input>
            </el-form-item>
            <el-form-item label="通知类型" prop="notificationType">
              <el-select v-model="notificationForm.notificationType" placeholder="请选择通知类型" style="width: 100%">
                <el-option label="班级通知" value="class"></el-option>
                <el-option label="学生通知" value="student"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="通知对象" prop="targetIds">
              <el-select 
                v-model="notificationForm.targetIds" 
                multiple 
                filterable 
                placeholder="请选择通知对象" 
                style="width: 100%"
              >
                <el-option 
                  v-for="item in targetOptions" 
                  :key="item.id" 
                  :label="item.name" 
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="notificationForm.priority" placeholder="请选择优先级" style="width: 100%">
                <el-option label="低" value="low"></el-option>
                <el-option label="中" value="normal"></el-option>
                <el-option label="高" value="high"></el-option>
              </el-select>
            </el-form-item>
            <div class="form-actions">
              <el-button @click="closeNotificationForm">取消</el-button>
              <el-button type="primary" @click="sendNotification">发送</el-button>
            </div>
          </el-form>
        </div>
      </el-popover>
      
      <!-- 通知详情弹窗 -->
      <el-dialog
        v-model="notificationDetailVisible"
        :title="currentNotification.title || '通知详情'"
        width="500px"
        destroy-on-close
      >
        <div class="notification-detail" v-if="currentNotification">
          <div class="notification-detail-meta">
            <div class="notification-detail-sender">发送人：{{ currentNotification.senderName || currentNotification.sender_name || '系统' }}</div>
            <div class="notification-detail-time">{{ formatDate(currentNotification.sendTime || currentNotification.createTime) }}</div>
          </div>
          <div class="notification-detail-content">{{ currentNotification.content }}</div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="notificationDetailVisible = false">关闭</el-button>
            <el-button 
              type="danger" 
              v-if="userStore.userInfo.role === 'admin' || 
                    (userStore.userInfo.role === 'teacher' && 
                     userStore.userInfo.schoolNumber === (currentNotification.senderId || currentNotification.sender_id))"
              @click="handleDeleteNotification"
            >
              删除
            </el-button>
          </span>
        </template>
      </el-dialog>

      <el-popover placement="bottom" width="330" trigger="hover">
        <div class="user-info">
          <div class="user-details">
            <el-icon class="input-icon" style="font-size: 24px;">
              <UserFilled />
            </el-icon>
            <div style="margin-left: 10px;">系统ID：459190</div>
          </div>
        </div>
        <div class="actions" style="margin-top: 20px;">
          <el-button plain @click="dialogVisible = true">
            账号信息
          </el-button>
          <el-button @click="changePassword">修改密码</el-button>
          <el-button @click="logout">退出登录</el-button>
        </div>

        <!-- 账号信息弹窗 -->
        <el-dialog v-model="dialogVisible" title="账号信息" width="620px">
          <div class="account-info">
            <!-- 图片居中 -->
            <div class="avatar-container">
              <img src="../assets/img/tx.jpg" alt="用户头像" class="avatar" />
            </div>

            <!-- 账号、角色信息 -->
            <div class="detail-item">
              <div class="label-value">
                <span class="label">账号：</span>
                <span class="value">{{ userStore.userInfo.username }}</span>
              </div>
              <el-button type="primary" size="small" plain @click="editPhone">修改账号</el-button>
            </div>
            <div class="detail-item">
              <div class="label-value">
                <span class="label">姓名：</span>
                <span class="value">{{ userStore.userInfo.realName || '未设置' }}</span>
              </div>
              <el-button type="primary" size="small" plain @click="editName">修改姓名</el-button>
            </div>
            <div class="detail-item">
              <div class="label-value">
                <span class="label">角色：</span>
                <span class="value">{{ userStore.userInfo.role === 'teacher' ? '教师' : '学生' }}</span>
              </div>
            </div>
            <div class="detail-item">
              <div class="label-value">
                <span class="label">创建时间：</span>
                <span class="value">{{ formatDate(userStore.userInfo.createTime) }}</span>
              </div>
            </div>
          </div>
          
        </el-dialog>
        <!-- 修改密码弹窗 -->
        <el-dialog v-model="changePasswordVisible" title="修改密码" width="400px" center class="password-dialog">
          <div class="password-form-container">
            <div class="dialog-header-image">
              <el-icon :size="50" class="lock-icon"><Lock /></el-icon>
            </div>
            <el-form
              :model="changePasswordForm"
              :rules="changePasswordRules"
              ref="changePasswordFormRef"
              label-position="top"
              class="password-form"
            >
              <el-form-item label="新密码" prop="newPassword" class="custom-form-item">
                <el-input
                  v-model="changePasswordForm.newPassword"
                  type="password"
                  show-password
                  placeholder="请输入新密码"
                  class="custom-input"
                >
                  <template #prefix>
                    <el-icon class="input-icon"><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="confirmPassword" class="custom-form-item">
                <el-input
                  v-model="changePasswordForm.confirmPassword"
                  type="password"
                  show-password
                  placeholder="请再次输入新密码"
                  class="custom-input"
                >
                  <template #prefix>
                    <el-icon class="input-icon"><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="验证码" prop="verifyCode" class="custom-form-item">
                <div class="verify-code-container">
                  <el-input
                    v-model="changePasswordForm.verifyCode"
                    placeholder="请输入验证码"
                    class="verify-code-input"
                  >
                    <template #prefix>
                      <el-icon class="input-icon"><Lock /></el-icon>
                    </template>
                  </el-input>
                  <div class="verify-code-img">
                    <VerifyCode ref="verifyCodeRef" @update:key="handleVerifyCodeKeyUpdate"/>
                  </div>
                </div>
              </el-form-item>
            </el-form>
            <div class="dialog-footer">
              <el-button @click="changePasswordVisible = false" class="cancel-btn">取 消</el-button>
              <el-button type="primary" @click="handleChangePassword(changePasswordFormRef)" class="confirm-btn">确 定</el-button>
            </div>
          </div>
        </el-dialog>
        <!-- 修改账号弹窗 -->
        <el-dialog v-model="editPhoneVisible" title="修改账号" width="400px" center class="edit-dialog">
          <div class="edit-form-container">
            <div class="dialog-header-image">
              <el-icon :size="50" class="edit-icon"><UserFilled /></el-icon>
            </div>
            <el-form
              :model="editPhoneForm"
              :rules="editPhoneRules"
              ref="editPhoneFormRef"
              label-position="top"
              class="edit-form"
            >
              <el-form-item label="新账号" prop="username" class="custom-form-item">
                <el-input
                  v-model="editPhoneForm.username"
                  placeholder="请输入新账号"
                  class="custom-input"
                >
                  <template #prefix>
                    <el-icon class="input-icon"><UserFilled /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-form>
            <div class="dialog-footer">
              <el-button @click="editPhoneVisible = false" class="cancel-btn">取 消</el-button>
              <el-button type="primary" @click="handleEditPhone(editPhoneFormRef)" class="confirm-btn">确 定</el-button>
            </div>
          </div>
        </el-dialog>
        <!-- 修改姓名弹窗 -->
        <el-dialog v-model="editNameVisible" title="修改姓名" width="400px" center class="edit-dialog">
          <div class="edit-form-container">
            <div class="dialog-header-image">
              <el-icon :size="50" class="edit-icon"><UserFilled /></el-icon>
            </div>
            <el-form
              :model="editNameForm"
              :rules="editNameRules"
              ref="editNameFormRef"
              label-position="top"
              class="edit-form"
            >
              <el-form-item label="新姓名" prop="realName" class="custom-form-item">
                <el-input
                  v-model="editNameForm.realName"
                  placeholder="请输入新姓名"
                  class="custom-input"
                >
                  <template #prefix>
                    <el-icon class="input-icon"><UserFilled /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-form>
            <div class="dialog-footer">
              <el-button @click="editNameVisible = false" class="cancel-btn">取 消</el-button>
              <el-button type="primary" @click="handleEditName(editNameFormRef)" class="confirm-btn">确 定</el-button>
            </div>
          </div>
        </el-dialog>
        <template #reference>
          <img src="../assets/img/sz.png" alt=""
            style="width: 37px; height: 37px; cursor: pointer; margin-right: 25px;">
        </template>

      </el-popover>
    </div>

    <div style="display: flex; justify-content: space-between; margin-top: 25px; gap: 20px;">
      <!-- 创建考试 -->
      <el-card style="width: calc(100% - 420px); margin-left: 20px;">
        <div class="card-container">
          <el-card shadow="hover" style="width: 48%; height: 100px;" @click="goToCreateExam">
            <div style="display: flex; align-items: center;">
              <img src="../assets/img/1.png" style="width: 60px; height: 60px; margin-right: 8px;">
              <div slot="header" class="clearfix">
                <span style="font-size: 18px;">创建考试</span>
                <div style="font-size: 13px; color: #909399; margin-top: 7px;">快速创建并发布在线考试<br>支持三种试题组卷模式</div>
              </div>
            </div>
          </el-card>
          <el-card shadow="hover" style="width: 48%; height: 100px;" @click="goToStudentManage">
            <div style="display: flex; align-items: center;">
              <img src="../assets/img/5.png" style="width: 60px; height: 50px; margin-right: 8px;">
              <div slot="header" class="clearfix">
                <span style="font-size: 18px;">考生管理</span>
                <div style="font-size: 13px; color: #909399; margin-top: 7px;">考生及组织信息统一管理<br>支持Excel考生</div>
              </div>
            </div>
          </el-card>
          <el-card shadow="hover" style="width: 48%; height: 100px;" @click="goToQuestionBank">
            <div style="display: flex; align-items: center;">
              <img src="../assets/img/6.png" style="width: 60px; height: 50px; margin-right: 8px;">
              <div slot="header" class="clearfix">
                <span style="font-size: 18px;">试题库</span>
                <div style="font-size: 13px; color: #909399; margin-top: 7px;">无限层级试题分类管理<br>支持多种题型创建</div>
              </div>
            </div>
          </el-card>
          <el-card shadow="hover" style="width: 48%; height: 100px;" @click="goToCertificate">
            <div style="display: flex; align-items: center;">
              <img src="../assets/img/4.png" style="width: 60px; height: 50px; margin-right: 8px;">
              <div slot="header" class="clearfix">
                <span style="font-size: 18px;">创建证书</span>
                <div style="font-size: 13px; color: #909399; margin-top: 7px;">为考试成绩设计证书模板<br>一键生成考生证书</div>
              </div>
            </div>
          </el-card>
        </div>
      </el-card>
      <!-- 系统概览 -->
      <el-card style="width: 360px; height: 300px; margin-right: 20px;">
        <template #header>
          <div class="card-header">
            <span style="font-weight: bold;">系统概览</span>
          </div>
        </template>
        
        <!-- 考试统计 -->
        <div class="overview-section">
          <div class="overview-item">
            <div class="overview-label">
              <el-icon><Document /></el-icon>
              <span>考试总数</span>
            </div>
            <div class="overview-value">{{ overviewData.examCount }}</div>
          </div>
          <div class="overview-item">
            <div class="overview-label">
              <el-icon><User /></el-icon>
              <span>考生总数</span>
            </div>
            <div class="overview-value">{{ overviewData.studentCount }}</div>
          </div>
          <div class="overview-item">
            <div class="overview-label">
              <el-icon><Collection /></el-icon>
              <span>题库总量</span>
            </div>
            <div class="overview-value">{{ overviewData.questionCount }}</div>
          </div>
          <div class="overview-item">
            <div class="overview-label">
              <el-icon><Finished /></el-icon>
              <span>已完成考试</span>
            </div>
            <div class="overview-value">{{ overviewData.completedExamCount }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 数据统计区域 -->
    <div style="padding: 15px 20px;">
      <el-row :gutter="15">
        <!-- 最近考试列表 -->
        <el-col :span="14">
          <el-card class="box-card">
            <template #header>
              <div class="card-header">
                <span style="font-weight: bold;">最近考试</span>
              </div>
            </template>
            <div style="height: 280px; overflow-y: auto;">
              <el-table :data="recentExams" style="width: 100%">
                <el-table-column prop="name" label="考试名称" width="180" />
                <el-table-column prop="date" label="考试时间" width="180" />
                <el-table-column prop="subject" label="科目" width="100" />
                <el-table-column prop="duration" label="考试时长" width="100" />
                <el-table-column prop="totalScore" label="总分" width="100" />
                <el-table-column prop="status" label="状态" />
              </el-table>
            </div>
          </el-card>
        </el-col>

        <!-- 成绩分布图表 -->
        <el-col :span="10">
          <el-card class="box-card">
            <template #header>
              <div class="card-header">
                <span style="font-weight: bold;">成绩分布</span>
              </div>
            </template>
            <!-- 筛选条件区域 -->
            <div style="display: flex; gap: 16px; margin-bottom: 12px;">
              <el-select v-model="selectedClass" placeholder="请选择班级" style="width: 120px;">
                <el-option label="全部班级" value=""></el-option>
                <el-option v-for="item in classList" :key="item.class_id" :label="item.class_name" :value="item.class_id"></el-option>
              </el-select>
              <el-select v-model="selectedPaper" placeholder="请选择试卷" style="width: 140px;" :disabled="!selectedClass">
                <el-option label="全部试卷" value=""></el-option>
                <el-option v-for="item in paperList" :key="item.examId || item.id || item.exam_id" :label="item.examName || item.name || item.exam_name" :value="item.examId || item.id || item.exam_id"></el-option>
              </el-select>
            </div>
            <div id="scoreDistributionChart" style="height: 280px;"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
  </div>
</template>

<script setup>
import { computed } from 'vue'
const studentListArr = computed(() => studentList.value)
const classListArr = computed(() => classList.value)
import { ref, reactive, onMounted, watch } from 'vue';
import { HomeFilled, UserFilled, Document, User, Collection, Finished, Lock, Message, Bell } from '@element-plus/icons-vue';
import { useUser } from '../stores/userInfo.js';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import * as echarts from 'echarts';
import request from '../utils/request';
import { JSEncrypt } from 'jsencrypt';
import { getSystemOverview } from '../api/dashboard';
import axios from 'axios';
import { getRecentExams, getClassID, getExamByClassID, getPieChart } from '@/api/exam'
import { notificationApi } from '../api/notification';
import VerifyCode from '@/components/VerifyCode.vue';

const activeIndex = ref('1');
const userStore = useUser();
const userInfo = ref(userStore.userInfo);
const router = useRouter();

// 通知相关数据
const unreadCount = ref(0);
const notificationFormRef = ref();
const notificationPopoverVisible = ref(false);
const notificationActiveTab = ref(userStore.userInfo.role === 'teacher' ? 'send' : 'center'); // 根据角色默认显示
const notifications = ref([]);
const totalNotifications = ref(0);
const notificationCurrentPage = ref(1);
const notificationPageSize = ref(10);
const notificationDetailVisible = ref(false);
const currentNotification = ref({});

// 通知表单数据，确保与后端 NotificationDto 字段一致
const notificationForm = reactive({
  title: '',           // 通知标题
  content: '',         // 通知内容
  notificationType: 'class', // 通知类型：class, student
  targetIds: [],       // 目标ID列表
  priority: 'normal'   // 优先级：low, normal, high
});

// 通知表单验证规则
const notificationRules = reactive({
  title: [{ required: true, message: '请输入通知标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入通知内容', trigger: 'blur' }],
  notificationType: [{ required: true, message: '请选择通知类型', trigger: 'change' }],
  targetIds: [{ 
    required: true, 
    validator: (rule, value, callback) => {
      if (!value || value.length === 0) {
        callback(new Error('请选择通知对象'));
      } else {
        callback();
      }
    }, 
    trigger: 'change' 
  }]
});
const targetOptions = ref([]);

// 打开通知表单
const openNotificationForm = () => {
  // 根据通知类型加载目标选项
  loadTargetOptions();
};

// 切换通知表单显示状态
const toggleNotificationForm = () => {
  notificationPopoverVisible.value = !notificationPopoverVisible.value;
  if (notificationPopoverVisible.value) {
    // 打开弹窗时加载数据
    if (notificationActiveTab.value === 'center') {
      fetchNotifications();
    } else if (userStore.userInfo.role === 'teacher') {
      loadTargetOptions();
    }
  }
};

// 关闭通知表单
const closeNotificationForm = () => {
  notificationFormRef.value?.resetFields();
  notificationPopoverVisible.value = false;
};

// 根据通知类型加载目标选项
const loadTargetOptions = async () => {
  if (notificationForm.notificationType === 'all') {
    targetOptions.value = [];
    return;
  }
  
  try {
    const teacherId = userStore.userInfo.schoolNumber;
    
    if (notificationForm.notificationType === 'class') {
      // 使用ExaminationmanagementController中的getTeacherClasses接口获取班级列表
      const response = await request({
        url: '/getTeacherClasses',
        method: 'get',
        params: { teacherId },
        headers: {
          'Authorization': sessionStorage.getItem('token')
        }
      });
      
      if (response.code === 200 && Array.isArray(response.data)) {
        targetOptions.value = response.data.map(item => ({
          id: item.classId || item.class_id,
          name: item.className || item.class_name
        }));
      } else {
        ElMessage.warning('未获取到班级数据');
        targetOptions.value = [];
      }
    } else if (notificationForm.notificationType === 'student') {
      // 使用ExaminationmanagementController中的getTeacherStudents接口获取学生列表
      const response = await request({
        url: '/getTeacherStudents',
        method: 'get',
        params: { teacherId },
        headers: {
          'Authorization': sessionStorage.getItem('token')
        }
      });
      
      if (response.code === 200 && Array.isArray(response.data)) {
        targetOptions.value = response.data.map(item => ({
          id: item.schoolNumber,
          name: `${item.name || ''} (${item.schoolNumber}) - ${item.className || ''}`
        }));
      } else {
        ElMessage.warning('未获取到学生数据');
        targetOptions.value = [];
      }
    }
  } catch (error) {
    console.error('加载目标选项失败:', error);
    ElMessage.error('加载目标选项失败，请重试');
    targetOptions.value = [];
  }
};

// 监听通知类型变化
watch(() => notificationForm.notificationType, (newType) => {
  notificationForm.targetIds = [];
  // 确保弹窗保持打开状态
  if (notificationPopoverVisible.value && notificationActiveTab.value === 'send') {
    loadTargetOptions();
  }
});

// 发送通知
const sendNotification = async () => {
  if (!notificationFormRef.value) return;
  
  await notificationFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const senderId = userStore.userInfo.schoolNumber;
        
        // 确保与后端 NotificationDto 字段一致
        const notificationDto = {
          title: notificationForm.title,
          content: notificationForm.content,
          notificationType: notificationForm.notificationType,
          targetIds: notificationForm.targetIds,
          priority: notificationForm.priority
        };
        
        const response = await notificationApi.sendNotification(notificationDto, senderId);
        
        if (response.code === 200) {
          ElMessage.success('通知发送成功');
          closeNotificationForm();
          // 重置表单
          notificationFormRef.value.resetFields();
          // 刷新未读通知数量
          fetchUnreadCount();
        } else {
          ElMessage.error(response.message || '通知发送失败');
        }
      } catch (error) {
        console.error('发送通知失败:', error);
        ElMessage.error(error.response?.data?.message || '发送通知失败，请重试');
      }
    }
  });
};

// 获取未读通知数量
const fetchUnreadCount = async () => {
  try {
    const studentId = userStore.userInfo.schoolNumber;
    const response = await notificationApi.getUnreadCount(studentId);
    
    if (response.code === 200 && response.data) {
      unreadCount.value = response.data.count || 0;
    }
  } catch (error) {
    console.error('获取未读通知数量失败:', error);
  }
};

// 先声明所有用到的ref变量，避免引用错误
const selectedClass = ref('');
const selectedPaper = ref('');
const paperList = ref([]);
const classList = ref([]);

// 格式化日期函数
const formatDate = (dateString) => {
  if (!dateString) return '未知';
  try {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return '未知';
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  } catch (error) {
    console.error('日期格式化错误：', error);
    return '未知';
  }
};

const dialogVisible = ref(false);
const changePasswordVisible = ref(false);
const editPhoneVisible = ref(false);
const editNameVisible = ref(false);

const changePasswordForm = reactive({
  newPassword: '',
  confirmPassword: '',
  verifyCode: '',
  verifyCodeKey: ''
});

const editPhoneForm = reactive({
  username: ''
});

const editNameForm = reactive({
  realName: ''
});

const changePasswordRules = reactive({
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== changePasswordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '验证码长度为4位', trigger: 'blur' }
  ]
});

const editPhoneRules = reactive({
  username: [
    { required: true, message: '请输入新账号', trigger: 'blur' },
    { min: 3, message: '账号长度至少为3位', trigger: 'blur' }
  ]
});

const editNameRules = reactive({
  realName: [
    { required: true, message: '请输入新姓名', trigger: 'blur' },
    { min: 2, message: '姓名长度至少为2位', trigger: 'blur' }
  ]
});

const changePasswordFormRef = ref();
const editPhoneFormRef = ref();
const editNameFormRef = ref();
const verifyCodeRef = ref(null);

// 处理验证码key更新
const handleVerifyCodeKeyUpdate = (newKey) => {
  changePasswordForm.verifyCodeKey = newKey;
};

// 获取验证码图片 - 不再需要这个函数，由VerifyCode组件处理
// const verifyCodeImg = ref('');
// const getVerifyCode = async () => { ... }

// RSA 公钥
const PUBLIC_KEY = `MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7rYgHiByM6LUO1Z7ZD80OKWl1O16/c+D1zRrrP5rYq/YSG+ZuP7Bjx3tcOgFmKL97ifyAbdNn9RmvyqBRqMt8YlT9vYXYQ8MirWbnBulhC9Q9j2ab/sUIDd1qdDIuAxx5i7X377M/IIrMTe1HTID646kwkKr/eUMZ1EEjX/Xnk2lJxj3sSzKuQ+LPMLrFQ1LP1jM6MNB4auDkrQ2vNEoI41gMy0PEE168nYrQWGkRdbolDX5GNDragi9my+Uv4J2hvf1GYDzDFs+FLK5ceUKFkkoGRHouqxkizxNAC2GlMGkJdKp2NXmvDdYvXl8VGutHPN2TnL2c875dRBEHb81zQIDAQAB`;

// RSA 加密函数
const encryptPassword = (password) => {
  const encryptor = new JSEncrypt();
  encryptor.setPublicKey(PUBLIC_KEY);
  return encryptor.encrypt(password);
};

const handleChangePassword = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 加密新密码
        const encryptedPassword = encryptPassword(changePasswordForm.newPassword);
        
        const response = await request({
          url: '/nerv/test',
          method: 'post',
          data: {
            username: userStore.userInfo.username,
            school_number: userStore.userInfo.schoolNumber,
            password: encryptedPassword,
            verifyCode: changePasswordForm.verifyCode,
            verifyCodeKey: changePasswordForm.verifyCodeKey
          }
        });

        if (response.code === 200) {
          ElMessage.success('密码修改成功');
          changePasswordVisible.value = false;
          // 重置表单
          changePasswordForm.newPassword = '';
          changePasswordForm.confirmPassword = '';
          changePasswordForm.verifyCode = '';
          changePasswordForm.verifyCodeKey = '';
        } else {
          ElMessage.error(response.message || '密码修改失败');
          // 刷新验证码
          getVerifyCode();
        }
      } catch (error) {
        console.error('修改密码错误：', error);
        ElMessage.error(error.response?.data?.message || '密码修改失败，请重试');
        // 刷新验证码
        getVerifyCode();
      }
    }
  });
};

// 监听弹窗打开，获取验证码
watch(changePasswordVisible, (newVal) => {
  if (newVal && verifyCodeRef.value) {
    // 使用组件的方法刷新验证码
    verifyCodeRef.value.handleClick();
  }
});

const handleEditPhone = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        const response = await request({
          url: '/nerv/updateUser',
          method: 'post',
          data: {
            id: userStore.userInfo.id,
            schoolNumber: userStore.userInfo.schoolNumber,
            username: editPhoneForm.username
          }
        });

        if (response.code === 200) {
          ElMessage.success('账号修改成功');
          editPhoneVisible.value = false;
          // 更新用户信息
          userStore.userInfo.username = editPhoneForm.username;
          // 重置表单
          editPhoneForm.username = '';
        } else {
          ElMessage.error(response.message || '账号修改失败');
        }
      } catch (error) {
        console.error('修改账号错误：', error);
        ElMessage.error('账号修改失败，请重试');
      }
    }
  });
};

const handleEditName = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        const response = await request({
          url: '/nerv/updateUser',
          method: 'post',
          data: {
            id: userStore.userInfo.id,
            schoolNumber: userStore.userInfo.schoolNumber,
            realName: editNameForm.realName
          }
        });

        if (response.code === 200) {
          ElMessage.success('姓名修改成功');
          editNameVisible.value = false;
          // 更新用户信息
          userStore.userInfo.realName = editNameForm.realName;
          // 重置表单
          editNameForm.realName = '';
        } else {
          ElMessage.error(response.message || '姓名修改失败');
        }
      } catch (error) {
        console.error('修改姓名错误：', error);
        ElMessage.error('姓名修改失败，请重试');
      }
    }
  });
};

const changePassword = () => {
  changePasswordVisible.value = true;
};

const handleSelect = (key) => {
  switch (key) {
    case '1':
      router.push('/main');
      break;
    case '2':
      router.push('/exam'); // 修改为正确的考试管理页面路由
      break;
    case '3':
      router.push('/practice'); // 练习页面
      break;
    case '5':
      router.push('/question-bank'); // 试题页面
      break;
    case '6':
      router.push('/student-manage'); // 人员管理页面
      break;
    case '7':
      router.push('/certificate'); // 证书页面
      break;
    default:
      break;
  }
};

const editPhone = () => {
  editPhoneVisible.value = true;
};

const editName = () => {
  editNameVisible.value = true;
};

const logout = () => {
  console.log('退出登录');
  router.push('/');
};

// 添加跳转到考生管理页面的方法
const goToStudentManage = () => {
  router.push('/student-manage');
};

// 在 script setup 部分添加
const goToQuestionBank = () => {
  router.push('/question-bank');
};

// 在 script setup 部分添加
const goToCreateExam = () => {
  router.push('/ex/create-exam');
};

// 在 script setup 部分添加
const goToCertificate = () => {
  router.push('/certificate');
};

// 最近考试数据
const recentExams = ref([])

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取最近考试列表
const fetchRecentExams = async () => {
  try {
    const response = await getRecentExams()
    if (response.code === 200) {
      recentExams.value = response.data.map(exam => ({
        name: exam.examName,
        date: formatDateTime(exam.startTime),
        subject: exam.subject,
        duration: exam.duration,
        totalScore: exam.totalScore,
        status: exam.status
      }))
    } else {
      ElMessage.error(response.message || '获取最近考试失败')
    }
  } catch (error) {
    console.error('获取最近考试失败:', error)
    ElMessage.error('获取最近考试失败')
  }
}

let myChart = null;
const initScoreDistributionChart = (chartData) => {
  const chartDom = document.getElementById('scoreDistributionChart');
  if (!chartDom) return;
  if (!myChart) {
    myChart = echarts.init(chartDom);
    window.addEventListener('resize', () => {
      myChart && myChart.resize();
    });
  }
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: (params) => `${params.name}: ${params.value}%`
    },
    legend: {
      orient: 'horizontal',
      top: 'bottom',
      data: ['优秀(90-100)', '良好(80-89)', '中等(70-79)', '及格(60-69)', '不及格(0-59)']
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '45%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 4,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: (params) => `${params.name}: ${params.value}%`
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        data: chartData || [
          { value: 0, name: '优秀(90-100)', itemStyle: { color: '#91cc75' } },
          { value: 0, name: '良好(80-89)', itemStyle: { color: '#5470c6' } },
          { value: 0, name: '中等(70-79)', itemStyle: { color: '#fac858' } },
          { value: 0, name: '及格(60-69)', itemStyle: { color: '#ee6666' } },
          { value: 0, name: '不及格(0-59)', itemStyle: { color: '#73c0de' } }
        ]
      }
    ]
  };
  myChart.setOption(option, true);
};

// 监听班级和试卷选择，获取饼图数据
watch([selectedClass, selectedPaper], async ([classId, examId]) => {
  if (classId && examId) {
    const res = await getPieChart(classId, examId);
    if (res.code === 200 && res.data) {
      let pieData = res.data;
      if (typeof pieData === 'string') {
        try {
          pieData = JSON.parse(pieData);
        } catch (e) {
          pieData = {};
        }
      }
      // 转换为ECharts需要的格式
      const chartData = [
        { value: parseFloat((pieData['优秀率']||'0').replace('%','')), name: '优秀(90-100)', itemStyle: { color: '#91cc75' } },
        { value: parseFloat((pieData['良好率']||'0').replace('%','')), name: '良好(80-89)', itemStyle: { color: '#5470c6' } },
        { value: parseFloat((pieData['中等率']||'0').replace('%','')), name: '中等(70-79)', itemStyle: { color: '#fac858' } },
        { value: parseFloat((pieData['及格率']||'0').replace('%','')), name: '及格(60-69)', itemStyle: { color: '#ee6666' } },
        { value: parseFloat((pieData['不及格率']||'0').replace('%','')), name: '不及格(0-59)', itemStyle: { color: '#73c0de' } }
      ];
      initScoreDistributionChart(chartData);
    } else {
      ElMessage.warning(res.message || '未获取到饼图数据');
      initScoreDistributionChart();
    }
  } else {
    // 未选择时清空
    initScoreDistributionChart();
  }
});

// 系统概览数据
const overviewData = ref({
  examCount: 0,
  studentCount: 0,
  questionCount: 0,
  completedExamCount: 0
});

const fetchOverviewData = async () => {
  try {
    const response = await axios.get('http://localhost:8080/dashboard/overview', {
      headers: {
        'Authorization': sessionStorage.getItem('token')
      }
    })
    if (response.data.code === 200) {
      overviewData.value = response.data.data
    } else {
      ElMessage.error(response.data.message || '获取系统概览数据失败')
    }
  } catch (error) {
    console.error('获取系统概览数据出错：', error)
    if (error.response) {
      console.error('错误响应:', error.response)
      ElMessage.error(error.response.data?.message || '获取系统概览数据失败')
    } else if (error.request) {
      console.error('请求未收到响应')
      ElMessage.error('服务器未响应，请检查网络连接')
    } else {
      console.error('请求配置错误:', error.message)
      ElMessage.error('请求配置错误')
    }
  }
}

// 获取班级列表（使用新接口）
const fetchClassList = async () => {
  try {
    const teacherId = userStore.userInfo.schoolNumber;
    const res = await getClassID(teacherId);
    if (res.code === 200 && Array.isArray(res.data)) {
      classList.value = res.data;
    } else {
      classList.value = [];
    }
  } catch (e) {
    classList.value = [];
  }
};

// 监听班级选择变化，获取试卷列表
watch(selectedClass, async (newVal) => {
  selectedPaper.value = '';
  paperList.value = [];
  if (newVal) {
    const res = await getExamByClassID(newVal);
    if (res.code === 200 && Array.isArray(res.data)) {
      paperList.value = res.data;
    }
  }
});

onMounted(() => {
  fetchRecentExams();
  initScoreDistributionChart();
  fetchOverviewData();
  fetchClassList();
  // 加载未读通知数量
  fetchUnreadCount();
});

// 获取通知列表
const fetchNotifications = async () => {
  try {
    let response;
    const userRole = userStore.userInfo.role;
    const userId = userStore.userInfo.schoolNumber;
    
    // 根据用户角色选择不同的通知接口
    if (userRole === 'admin') {
      // 管理员获取所有通知
      response = await notificationApi.getAllNotifications(
        notificationCurrentPage.value, 
        notificationPageSize.value
      );
    } else if (userRole === 'teacher') {
      // 教师获取自己发送的通知
      response = await notificationApi.getTeacherNotifications(
        userId,
        notificationCurrentPage.value, 
        notificationPageSize.value
      );
    } else {
      // 学生获取自己的通知
      response = await notificationApi.getStudentNotifications(
        userId, 
        notificationCurrentPage.value, 
        notificationPageSize.value
      );
    }
    
    if (response.code === 200 && response.data) {
      // 根据后端返回的数据结构进行处理
      if (Array.isArray(response.data)) {
        // 如果直接返回数组
        notifications.value = response.data;
        totalNotifications.value = response.data.length;
      } else if (response.data.notifications) {
        // 如果返回对象包含 notifications 字段
        notifications.value = response.data.notifications;
        totalNotifications.value = response.data.total || response.data.notifications.length;
      } else if (response.data.list) {
        // 如果返回对象包含 list 字段
        notifications.value = response.data.list;
        totalNotifications.value = response.data.total || response.data.list.length;
      } else {
        // 其他情况
        notifications.value = [];
        totalNotifications.value = 0;
        console.warn('未识别的通知数据结构:', response.data);
      }
    } else {
      ElMessage.warning(response.message || '获取通知列表失败');
      notifications.value = [];
      totalNotifications.value = 0;
    }
  } catch (error) {
    console.error('获取通知列表失败:', error);
    notifications.value = [];
    totalNotifications.value = 0;
  }
};

// 处理通知分页变化
const handleNotificationPageChange = (page) => {
  notificationCurrentPage.value = page;
  fetchNotifications();
};

// 查看通知详情
const viewNotification = async (notificationId) => {
  if (!notificationId) {
    ElMessage.warning('通知ID不存在');
    return;
  }
  
  try {
    const userId = userStore.userInfo.schoolNumber;
    const response = await notificationApi.getNotificationDetail(notificationId, userId);
    
    if (response.code === 200 && response.data) {
      // 确保通知对象有正确的ID字段
      currentNotification.value = {
        ...response.data,
        notificationId: response.data.notificationId || response.data.id || notificationId
      };
      notificationDetailVisible.value = true;
      
      // 只有学生需要标记为已读
      if (userStore.userInfo.role === 'student' && !response.data.readStatus) {
        await notificationApi.markAsRead(notificationId, userId);
        // 刷新未读数和通知列表
        fetchUnreadCount();
        fetchNotifications();
      }
    } else {
      ElMessage.warning(response.message || '获取通知详情失败');
    }
  } catch (error) {
    console.error('查看通知详情失败:', error);
    ElMessage.error('查看通知详情失败，请重试');
  }
};

// 删除通知
const handleDeleteNotification = async () => {
  if (!currentNotification.value) {
    ElMessage.warning('通知不存在');
    return;
  }
  
  // 获取通知ID，兼容不同的字段名称
  const notificationId = currentNotification.value.notificationId || currentNotification.value.id;
  
  if (!notificationId) {
    ElMessage.warning('通知ID不存在');
    return;
  }
  
  try {
    const response = await notificationApi.deleteNotification(notificationId);
    
    if (response.code === 200) {
      ElMessage.success('删除通知成功');
      notificationDetailVisible.value = false;
      // 刷新通知列表
      fetchNotifications();
      fetchUnreadCount();
    } else {
      ElMessage.error(response.message || '删除通知失败');
    }
  } catch (error) {
    console.error('删除通知失败:', error);
    ElMessage.error('删除通知失败，请重试');
  }
};

// 监听通知中心/发送通知切换
watch(() => notificationActiveTab.value, (newTab) => {
  if (newTab === 'center') {
    fetchNotifications();
  } else if (userStore.userInfo.role === 'teacher') {
    loadTargetOptions();
  }
});
</script>

<style scoped>
/* 主容器样式 */
.main-container {
  min-height: 100vh;
  position: relative;
  background: linear-gradient(135deg, #f0f7ff 0%, #ffffff 100%);
  overflow: hidden;
}

/* 通知图标样式 */
.notification-icon {
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.notification-icon:hover {
  transform: scale(1.1);
}

.notification-badge :deep(.el-badge__content) {
  background-color: #ff4d4f;
  border: none;
}

/* 通知表单样式 */
.notification-form {
  padding: 10px 15px;
}

.notification-form h3 {
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 18px;
  color: #333;
  text-align: center;
  position: relative;
  padding-bottom: 10px;
}

.notification-form h3::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 3px;
  background: linear-gradient(90deg, #1890ff, #40a9ff);
  border-radius: 3px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

:deep(.el-form) {
  margin-top: 15px;
}

:deep(.el-form-item) {
  margin-bottom: 15px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-form-item__error) {
  padding-top: 2px;
}

:deep(.el-textarea__inner) {
  min-height: 80px !important;
}

:deep(.el-dialog) {
  opacity: 1 !important;
  display: block !important;
  z-index: 3000 !important;
  background: #fff !important;
}
:deep(.el-overlay) {
  z-index: 2999 !important;
}
:deep(.el-dialog__wrapper) {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
}
/* 背景装饰元素 */
.background-decoration {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 0;
}

/* 动画效果 */
@keyframes float {
  0%, 100% {
    transform: translate(0, 0) rotate(0deg);
  }
  25% {
    transform: translate(10px, 10px) rotate(2deg);
  }
  50% {
    transform: translate(0, 20px) rotate(-2deg);
  }
  75% {
    transform: translate(-10px, 10px) rotate(1deg);
  }
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
    opacity: 0.1;
  }
  50% {
    transform: scale(1.05);
    opacity: 0.15;
  }
}

@keyframes wave {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

@keyframes shine {
  0% {
    background-position: -200% center;
  }
  100% {
    background-position: 200% center;
  }
}

/* 圆形装饰动画增强 */
.circle {
  position: absolute;
  border-radius: 50%;
  opacity: 0.1;
  animation: pulse 8s infinite ease-in-out;
}

.circle-1 {
  width: 400px;
  height: 400px;
  top: -100px;
  right: -100px;
  background: radial-gradient(circle, rgba(24, 144, 255, 0.2) 0%, rgba(24, 144, 255, 0.1) 50%, rgba(24, 144, 255, 0) 70%);
  animation: float 15s infinite ease-in-out;
}

.circle-2 {
  width: 300px;
  height: 300px;
  bottom: -50px;
  left: -50px;
  background: radial-gradient(circle, rgba(64, 169, 255, 0.2) 0%, rgba(64, 169, 255, 0.1) 50%, rgba(64, 169, 255, 0) 70%);
  animation: float 20s infinite ease-in-out reverse;
}

.circle-3 {
  width: 200px;
  height: 200px;
  top: 50%;
  left: 50%;
  background: radial-gradient(circle, rgba(145, 204, 117, 0.2) 0%, rgba(145, 204, 117, 0.1) 50%, rgba(145, 204, 117, 0) 70%);
  animation: float 25s infinite ease-in-out;
}

/* 线条装饰 */
.line {
  position: absolute;
  background: linear-gradient(90deg, rgba(24, 144, 255, 0.1) 0%, rgba(24, 144, 255, 0) 100%);
}

.line-1 {
  width: 100%;
  height: 1px;
  top: 30%;
  transform: rotate(-45deg);
  transform-origin: left;
}

.line-2 {
  width: 100%;
  height: 1px;
  bottom: 20%;
  transform: rotate(45deg);
  transform-origin: right;
}

/* 网格装饰 */
.grid {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    linear-gradient(rgba(24, 144, 255, 0.03) 1px, transparent 1px),
    linear-gradient(90deg, rgba(24, 144, 255, 0.03) 1px, transparent 1px);
  background-size: 20px 20px;
  animation: wave 20s linear infinite;
}

/* 全局样式 */
:deep(body) {
  background-color: #f0f2f5;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  color: #333;
}

/* 导航栏样式 */
.el-menu-demo {
  height: 60px;
  line-height: 60px;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.03);
  border-bottom: 1px solid #f0f0f0;
}

.el-menu-item {
  font-size: 16px;
  color: #666;
  font-weight: 500;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
}

:deep(.el-menu-item.is-active) {
  color: #1890ff !important;
  font-weight: 600;
}

.el-menu-item::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  width: 0;
  height: 2px;
  background: #1890ff;
  transition: all 0.3s ease;
  transform: translateX(-50%);
}

.el-menu-item:hover::after {
  width: 80%;
}

.header-right-icon {
  position: absolute;
  right: 20px;
  top: 0;
  height: 60px;
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-right-icon img {
  transition: transform 0.3s ease;
}

.header-right-icon img:hover {
  transform: scale(1.1);
}

/* 功能卡片区域 */
.card-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  padding: 8px;
}

.card-container .el-card {
  background: linear-gradient(135deg, #ffffff 0%, #f8fafd 100%);
  box-shadow: 
    0 4px 12px rgba(0, 0, 0, 0.05),
    0 1px 2px rgba(24, 144, 255, 0.05);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.03);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.card-container .el-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    120deg,
    transparent,
    rgba(255, 255, 255, 0.3),
    transparent
  );
  transition: 0.5s;
}

.card-container .el-card:hover::before {
  left: 100%;
}

.card-container .el-card:hover {
  transform: translateY(-5px) scale(1.02);
  box-shadow: 
    0 12px 28px rgba(0, 0, 0, 0.1),
    0 4px 8px rgba(24, 144, 255, 0.15);
}

.card-container .el-card img {
  padding: 10px;
  background: rgba(24, 144, 255, 0.05);
  border-radius: 8px;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.card-container .el-card:hover img {
  transform: scale(1.1) rotate(5deg);
}

.card-container .clearfix span {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  display: block;
}

.card-container .clearfix div {
  font-size: 13px;
  color: #999;
  line-height: 1.5;
}

/* 系统概览卡片 */
.overview-section {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  margin-bottom: 20px;
}

.section-title {
  font-size: 24px;
  color: #303133;
  margin-bottom: 20px;
  font-weight: 600;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.overview-card {
  transition: all 0.3s ease;
}

.overview-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-content {
  text-align: center;
  padding: 20px;
}

.card-value {
  font-size: 36px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 10px;
}

.card-label {
  font-size: 16px;
  color: #606266;
}

@media screen and (max-width: 768px) {
  .overview-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media screen and (max-width: 480px) {
  .overview-cards {
    grid-template-columns: 1fr;
  }
}

/* 最近考试表格 */
:deep(.el-table) {
  background: linear-gradient(135deg, #ffffff 0%, #f8fafd 100%);
  backdrop-filter: blur(10px);
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.03);
  height: 100%;
}

:deep(.el-table th) {
  background: linear-gradient(to bottom, #f8fafc, #f5f7fa) !important;
  font-weight: 600;
  color: #333;
  border-bottom: 1px solid rgba(240, 240, 240, 0.8);
  padding: 6px 0;
  font-size: 14px;
}

:deep(.el-table td) {
  padding: 6px 0;
  color: #333;
  font-size: 13px;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background: rgba(250, 251, 252, 0.7);
}

:deep(.el-table .cell) {
  text-align: center;
}

/* 成绩分布图表 */
#scoreDistributionChart {
  padding: 15px;
  border-radius: 8px;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafd 100%);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.8);
  box-shadow: 
    0 4px 12px rgba(0, 0, 0, 0.05),
    0 1px 2px rgba(24, 144, 255, 0.05);
}

/* 卡片通用样式 */
.box-card {
  border-radius: 8px;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafd 100%);
  box-shadow: 
    0 4px 12px rgba(0, 0, 0, 0.05),
    0 1px 2px rgba(24, 144, 255, 0.05);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.8);
  margin-bottom: 10px;
  border: none;
  height: calc(100% - 10px);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.box-card:hover {
  transform: translateY(-2px);
  box-shadow: 
    0 12px 28px rgba(0, 0, 0, 0.1),
    0 4px 8px rgba(24, 144, 255, 0.15);
}

.card-header span {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  position: relative;
  padding-left: 12px;
}

.card-header span::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background: linear-gradient(to bottom, #1890ff, #40a9ff);
  border-radius: 2px;
}

/* 数据统计区域间距 */
.el-row {
  margin: 10px 0;
}

/* 滚动条美化 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background: linear-gradient(to bottom, #c0c4cc, #d0d4dc);
  border-radius: 3px;
}

::-webkit-scrollbar-track {
  background: #f5f7fa;
  border-radius: 3px;
}

/* 账号信息弹窗样式优化 */
.account-info {
  padding: 20px;
}

.avatar-container {
  text-align: center;
  margin-bottom: 20px;
  position: relative;
  width: 100px;
  height: 100px;
  margin: 0 auto 20px;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.avatar-container:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 16px rgba(24, 144, 255, 0.15);
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

.detail-item {
  background: linear-gradient(120deg, #ffffff 0%, #f8fafd 100%);
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 1px solid rgba(240, 240, 240, 0.8);
  transition: all 0.3s ease;
}

.detail-item:hover {
  background: linear-gradient(120deg, #f0f7ff 0%, #ffffff 100%);
  border-color: rgba(24, 144, 255, 0.1);
  transform: translateX(5px);
}

.label-value {
  display: flex;
  align-items: center;
  gap: 10px;
}

.label {
  color: #666;
  font-size: 14px;
  font-weight: 500;
  min-width: 70px;
}

.value {
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  background: linear-gradient(120deg, #ffffff 0%, #f8fafd 100%);
}

:deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 15px 20px;
  border-top: 1px solid #f0f0f0;
  background: linear-gradient(120deg, #ffffff 0%, #f8fafd 100%);
}

/* 修改密码按钮样式 */
.detail-item .el-button {
  padding: 8px 15px;
  font-size: 13px;
}

.detail-item .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.15);
}

/* 弹窗动画效果 */
:deep(.el-dialog) {
  transform: translateY(-20px);
  opacity: 0;
  transition: all 0.3s ease-out;
}

:deep(.el-dialog.el-dialog--center) {
  transform: translateY(0);
  opacity: 1;
}

/* 用户信息弹出框样式优化 */
.user-info {
  padding: 15px;
}

.user-details {
  display: flex;
  align-items: center;
  padding: 10px;
  background: linear-gradient(120deg, #ffffff 0%, #f8fafd 100%);
  border-radius: 8px;
  border: 1px solid rgba(240, 240, 240, 0.8);
}

.actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 15px;
}

.actions .el-button {
  padding: 8px 15px;
  font-size: 13px;
}

/* 主容器背景动画 */
.main-container {
  background-size: 400% 400%;
  animation: wave 15s ease infinite;
  background-image: linear-gradient(
    135deg,
    #f0f7ff 0%,
    #ffffff 50%,
    #f0f7ff 100%
  );
}

/* 卡片阴影动画 */
.box-card {
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.box-card:hover {
  transform: translateY(-2px);
  box-shadow: 
    0 12px 28px rgba(0, 0, 0, 0.1),
    0 4px 8px rgba(24, 144, 255, 0.15);
}

/* 按钮动画增强 */
:deep(.el-button) {
  position: relative;
  overflow: hidden;
}

:deep(.el-button::before) {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    120deg,
    transparent,
    rgba(255, 255, 255, 0.4),
    transparent
  );
  transition: 0.5s;
}

:deep(.el-button:hover::before) {
  left: 100%;
}

:deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.15);
}

/* 修改密码弹窗样式 */
.password-dialog :deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  background: linear-gradient(135deg, #ffffff 0%, #f8fafd 100%);
}

.password-dialog :deep(.el-dialog__header) {
  text-align: center;
  padding: 20px 20px 0;
  margin: 0;
}

.password-dialog :deep(.el-dialog__title) {
  font-size: 20px;
  font-weight: 600;
  background: linear-gradient(45deg, #1890ff, #40a9ff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  letter-spacing: 1px;
}

.password-form-container {
  padding: 0 30px 30px;
}

.dialog-header-image {
  text-align: center;
  margin: 20px 0;
  position: relative;
}

.lock-icon {
  padding: 20px;
  border-radius: 50%;
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f7ff 100%);
  color: #1890ff;
  box-shadow: 0 8px 16px rgba(24, 144, 255, 0.15);
  animation: float 6s ease-in-out infinite;
}

.password-form {
  margin-top: 30px;
}

.custom-form-item {
  margin-bottom: 25px;
}

.custom-form-item :deep(.el-form-item__label) {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  font-weight: 500;
}

.custom-input :deep(.el-input__wrapper) {
  border-radius: 12px;
  background: linear-gradient(135deg, #f8fafd 0%, #ffffff 100%) !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05) !important;
  border: 1px solid rgba(24, 144, 255, 0.1);
  transition: all 0.3s ease;
}

.custom-input :deep(.el-input__wrapper:hover),
.custom-input :deep(.el-input__wrapper.is-focus) {
  border-color: #1890ff;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.1) !important;
  transform: translateY(-1px);
}

.custom-input :deep(.el-input__inner) {
  height: 42px;
  font-size: 14px;
  color: #333;
}

.custom-input :deep(.input-icon) {
  font-size: 16px;
  color: #1890ff;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
}

.cancel-btn,
.confirm-btn {
  width: 120px;
  height: 40px;
  font-size: 14px;
  border-radius: 20px;
  transition: all 0.3s ease;
}

.cancel-btn {
  background: linear-gradient(135deg, #f0f2f5 0%, #fafafa 100%);
  border: none;
  color: #666;
}

.confirm-btn {
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
  border: none;
  color: white;
}

.cancel-btn:hover,
.confirm-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.confirm-btn:hover {
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2);
}

@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

/* 添加输入框动画效果 */
.custom-input :deep(.el-input__wrapper) {
  position: relative;
  overflow: hidden;
}

.custom-input :deep(.el-input__wrapper::before) {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    120deg,
    transparent,
    rgba(24, 144, 255, 0.1),
    transparent
  );
  transition: 0.5s;
}

.custom-input :deep(.el-input__wrapper:hover::before) {
  left: 100%;
}

/* 错误提示美化 */
.custom-form-item :deep(.el-form-item__error) {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
  display: flex;
  align-items: center;
  opacity: 0.8;
}

/* 密码可见性图标美化 */
.custom-input :deep(.el-input__suffix) {
  color: #1890ff;
  transition: all 0.3s ease;
}

.custom-input :deep(.el-input__suffix:hover) {
  color: #40a9ff;
}

/* 弹窗打开动画 */
.password-dialog :deep(.el-dialog) {
  transform: scale(0.9);
  opacity: 0;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.password-dialog :deep(.el-dialog.el-dialog--center) {
  transform: scale(1);
  opacity: 1;
}

/* 表单项进入动画 */
.custom-form-item {
  animation: slideUp 0.5s ease forwards;
  opacity: 0;
  transform: translateY(20px);
}

.custom-form-item:nth-child(1) {
  animation-delay: 0.1s;
}

.custom-form-item:nth-child(2) {
  animation-delay: 0.2s;
}

.custom-form-item:nth-child(3) {
  animation-delay: 0.3s;
}

@keyframes slideUp {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 修改账号和姓名弹窗样式 */
.edit-dialog :deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  background: linear-gradient(135deg, #ffffff 0%, #f8fafd 100%);
}

.edit-dialog :deep(.el-dialog__header) {
  text-align: center;
  padding: 20px 20px 0;
  margin: 0;
}

.edit-dialog :deep(.el-dialog__title) {
  font-size: 20px;
  font-weight: 600;
  background: linear-gradient(45deg, #1890ff, #40a9ff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  letter-spacing: 1px;
}

.edit-form-container {
  padding: 0 30px 30px;
}

.edit-icon {
  padding: 20px;
  border-radius: 50%;
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f7ff 100%);
  color: #1890ff;
  box-shadow: 0 8px 16px rgba(24, 144, 255, 0.15);
  animation: float 6s ease-in-out infinite;
}

.edit-form {
  margin-top: 30px;
}

.verify-code-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.verify-code-input {
  flex: 1;
}

.verify-code-img {
  height: 42px;
  border-radius: 4px;
  cursor: pointer;
  overflow: hidden;
  width: 120px;
}

:deep(.verify-code-input .el-input__wrapper) {
  border-radius: 12px;
  background: linear-gradient(135deg, #f8fafd 0%, #ffffff 100%) !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05) !important;
  border: 1px solid rgba(24, 144, 255, 0.1);
  transition: all 0.3s ease;
}

/* 通知中心样式 */
.notification-header {
  padding: 10px 15px;
  border-bottom: 1px solid #eee;
}

.notification-tabs {
  display: flex;
  gap: 20px;
}

.notification-tab {
  padding: 5px 0;
  cursor: pointer;
  position: relative;
  font-weight: 500;
  color: #606266;
}

.notification-tab.active {
  color: #1890ff;
  font-weight: 600;
}

.notification-tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background: #1890ff;
  border-radius: 1px;
}

.notification-center {
  padding: 0;
  max-height: 400px;
  display: flex;
  flex-direction: column;
}

.empty-notifications {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}

.notification-item {
  display: flex;
  padding: 12px 15px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.3s ease;
}

.notification-item:hover {
  background-color: #f5f7fa;
}

.notification-item.unread {
  background-color: #f0f7ff;
}

.notification-priority {
  width: 4px;
  border-radius: 2px;
  margin-right: 10px;
}

.priority-high {
  background-color: #f56c6c;
}

.priority-normal {
  background-color: #e6a23c;
}

.priority-low {
  background-color: #67c23a;
}

.notification-content {
  flex: 1;
}

.notification-title {
  font-weight: 500;
  margin-bottom: 5px;
  color: #303133;
}

.notification-brief {
  font-size: 13px;
  color: #606266;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.notification-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.unread-badge {
  color: #1890ff;
  font-weight: 500;
}

.notification-pagination {
  padding: 10px;
  display: flex;
  justify-content: center;
  margin-top: auto;
}

/* 通知详情样式 */
.notification-detail {
  padding: 10px;
}

.notification-detail-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  font-size: 14px;
  color: #606266;
}

.notification-detail-content {
  font-size: 14px;
  line-height: 1.6;
  color: #303133;
  white-space: pre-wrap;
}
</style>